﻿using System;
using xxpl1.Cache;
using xxpl1.HTTP.Parser;
using xxpl1.HTTP.Runtime;
using xxpl1.Log;
using xxpl1.Utils;

namespace xxpl1.GAE.Simple2
{
    public class CheckCacheHandler2 : IHttpRequestHandler
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(CheckCacheHandler2));

        public void Execute(HandlerContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;

            if (Settings.Instance.EnableCache
                && "GET".Equals(request.Method, StringComparison.OrdinalIgnoreCase)
                )
            {
                byte[] cachedResponse = DiskCacheFactory.GetDiskCache().Get(request.RawUrl);

                if (cachedResponse != null)
                {
                    response.IsFromCache = true;

                    if (request.Headers.ContainsKey("If-Modified-Since")
                        || request.Headers.ContainsKey("If-None-Match"))
                    {
                        response.Send304();
                        logger.InfoFormat("HIT Cache 304: {0} {1}ms", request.RawUrl, request.ElapsedMs);
                        context.Result = HanlderReult.Ok;
                        return;
                    }

                    response.SendCache(cachedResponse);

                    logger.InfoFormat("HIT Cache 200: {0} {1}ms", request.RawUrl, request.ElapsedMs);
                    context.Result = HanlderReult.Ok;
                    return;
                }
            }

            context.Result = HanlderReult.NextHanler;
        }
    }
}
